#!/usr/bin/env python
# coding=utf-8

from google.appengine.api import memcache
from google.appengine.ext import db
import model
from api.myoauth import *
from location import members_in_memery

def get_member_by_username(name):
    one = memcache.get('Member::' + name)
    if one:
        return one
    else:
        q = db.GqlQuery("SELECT * FROM Member WHERE username = :1", name)
        if q.count() == 1:
            one = q[0]
            memcache.set('Member::' + name, one, 86400)
            return one
        else:
            return False
        
def get_member_by_id(uid):
    one = memcache.get("Member::" + str(uid))
    if one:
        return one
    else:
        q = Member.get_by_id(uid)
        if q is not None:
            memcache.set('Member::' + str(uid), q, 86400 * 365)
            return q
        
def get_member_by_access_token(access_token_key):
    one = memcache.get("Member::"+access_token_key)
    if one:
        return one
    else:
        q = db.GqlQuery("SELECT * FROM AccessToken WHERE access_token_key = :1",access_token_key)
        if q.count()==1:
            access_token = q[0]
            memcache.set("Member::"+access_token_key,access_token.token_owner,86400)
            return access_token.token_owner
        else:
            raise OAuthError("invalid access_token")